
#include "BSP_Config.h"

#include "BSP.h"
#include "IO.h"

uint32_t smState = 0;

static const IO_T smCLK = IO_INIT_TABLE(SM_CLK_GP, SM_CLK_PIN);
static const IO_T smSDI = IO_INIT_TABLE(SM_SDI_GP, SM_SDI_PIN);
static const IO_T smLE = IO_INIT_TABLE(SM_LE_GP, SM_LE_PIN);

void SM16106_Init(void){
	IO_Set(&smLE, 0);
	IO_Init(&smLE, IO_Mode_OUT);
	IO_Init(&smCLK, IO_Mode_OUT);
	IO_Init(&smSDI, IO_Mode_OUT);
	
	IO_Set(&smCLK, 0);
	IO_Set(&smSDI, 0);

	SM16106_Set(0xFFFF, 0x0000);
}

static void SM16106_Update(void){
	int i;
	
	IO_Set(&smLE, 0);
	for(i = 16; i > 0; ){
		--i;
		IO_Set(&smSDI, smState & (1 << i));
		IO_Set(&smCLK, 1);
		IO_Set(&smCLK, 0);
	}
	
	IO_Set(&smLE, 1);	
	IO_Set(&smLE, 0);
}

void SM16106_Set(uint32_t pins, uint32_t value){
	int i;
	
	for(i = 0; i < 16; i++){
		uint32_t mask = (1u << i);
		if(!(pins & mask)){
			continue;
		}
		
		if((value & mask) != 0){
			smState |= mask;
		}
		else{
			smState &= ~mask;
		}
	}
	
	SM16106_Update();
}

uint32_t SM16106_Get(void){
	return smState;
}



